package com.ze.familyday.familyphotoframesquare;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ze.commontool.HttpGetAllCnnt;
import com.ze.commontool.NetHelper;
import com.ze.commontool.PublicInfo;
import com.ze.familyday.familyphotoframesquare.R;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

public class PullImageService extends Service{

	public final static String TAG = "PullImageService";
	public boolean runFlag = false;
	public static String m_auth;
	public String NewestId;
	int testNum = 0;
	
	
	WakeLock mWakeLock;
	
	
	

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		runFlag = true;
		PublicInfo.runRequestFamily = true;
		if (m_auth == null)
			return;
		acquireWakeLock();
		new AsyncTask<Object, Object, JSONObject>(){

			@Override
			protected JSONObject doInBackground(Object... params) {
				// TODO Auto-generated method stub
				return HttpGetAllCnnt.getPhotoID(1, 1, m_auth);
			}

			@Override
			protected void onPostExecute(JSONObject result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result == null)
					return;
				try{
				if (!result.isNull("error") && result.getInt("error")==0){
					JSONArray array = new JSONArray();
					if (!result.isNull("data"))
						array = result.getJSONArray("data");
					if (array.length() >= 1){
						JSONObject object = array.getJSONObject(0);
						if (!object.isNull("id")) {
							NewestId = object.getString("id");
							Log.v(TAG, "第一次连接服务的最新的帖子id为：" + NewestId);
							new GetNewestIDTask().execute("");
						}
					}else {
						NewestId = "nopic";
						Log.v(TAG, "用户图片为空！");
						new GetNewestIDTask().execute("");
					}
				}
				}catch (Exception e){
					
					e.printStackTrace();
				}
			}
			
			
		}.execute("");
		
	}
	
	
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		runFlag = false;
		releaseWakeLock();
	}

	
	//申请设备电源锁
	private void acquireWakeLock()
    {
        if (null == mWakeLock)
        {
            PowerManager pm = (PowerManager)this.getSystemService(POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE,"");
            if (null != mWakeLock)
            {
                mWakeLock.acquire();
            }
        }
    }
	//释放设备电源锁
	private void releaseWakeLock()
    {
        if (null != mWakeLock)
        {
            mWakeLock.release();
            mWakeLock = null;
        }
    }
	

	class GetNewestIDTask extends AsyncTask<Object, Object, JSONObject>{

		String templateData;
		String requestFamily;
		
		@Override
		protected JSONObject doInBackground(Object... params) {
			// TODO Auto-generated method stub
			if (!runFlag)
				return null;
			
			//增加访问模板接口
			//templateData = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_temlate), m_auth);
			//增加访问申请家人接口
			if (PublicInfo.runRequestFamily) {
				requestFamily = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_request_family), m_auth);
			}
			return HttpGetAllCnnt.getPhotoID(5, 1, m_auth);
			
			
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (!runFlag)
				return;
			//处理模板
			//treatTemplate(templateData);
			//处理家人申请接口
			if (PublicInfo.runRequestFamily) {
				treatRequestFamily(requestFamily);
			}
			try {
				if (result != null && !result.isNull("error") && result.getInt("error") == 0){
					
					JSONArray array = result.getJSONArray("data");
					JSONArray tempArray = new JSONArray();
					
					if (NewestId.equals("nopic") && array.length() >= 1) {
						tempArray = array;
					}
					else {
						
						for (int i = 0; i < array.length(); i ++){
							JSONObject object = array.getJSONObject(i);
							
							int tempID = Integer.parseInt(object.getString("id"));
							if (tempID <= Integer.parseInt(NewestId))
								break;
							else {
								tempArray.put(object);
							}
							
						}
					}
					
					if (array.length() > 0)
						NewestId = array.getJSONObject(0).getString("id");
					Log.v(TAG, "新图片的数量为：" + tempArray.length());
					
					if (tempArray.length() > 0) {
						
						PhotoFrameActivity.mInstance.notifyPull(tempArray);
					}
					
					/*for (int i = 0; i < tempArray.length(); i ++){
						Log.v(TAG, "新图片的信息：" + tempArray.getJSONObject(i).toString());
						PhotoFrameActivity.instance.notifyPush(tempArray.getJSONObject(i).toString());
						Log.v(TAG, "最新帖子ID为：" + NewestId);
					}*/
					
				}
			}catch (Exception e){
				e.printStackTrace();
			}
			//Log.v(TAG, "第" + (++ testNum) + "次连接服务器！");
			new Handler().postDelayed(new Runnable() {
				public void run() {
					new GetNewestIDTask().execute("");
				}
			}, 20000);
			
		}
		
		
	}
	
	/**
	 * 模板处理
	 */
	public void treatTemplate(String data) {
		Log.v(TAG, data);
		try {
			JSONObject object = new JSONObject(data);
			if (object.getInt("error") == 0) {
				object = object.getJSONObject("data");
				if (!object.getString("pic").equals(PublicInfo.templateUrl)) {
					PublicInfo.templateUrl = object.getString("pic");
					
				}
			}
		} catch (Exception e) {
			PublicInfo.templateUrl = "default";
			return;
			
		}
		PhotoFrameActivity.mInstance.useTemplate(PublicInfo.templateUrl);
	}
	
	/**
	 * 家人申请处理
	 */
	public void treatRequestFamily(String string) {
		Log.v(TAG, "家人申请数据：" + string);
		if (string == null || string.equals("")) {
			return;
		}
		try {
			JSONObject object = new JSONObject(string);
			if (object.getInt("error") == 0) {
				object = object.getJSONObject("data");
				JSONArray array = object.getJSONArray("requestlist");
				if (array.length() >= 1) {
					object = array.getJSONObject(0);
					PublicInfo.runRequestFamily = false;
					PhotoFrameActivity.mInstance.showFamilyDialog(object);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.v(TAG, "exception from treatRequestFamily");
		}
	}

}
